package service

import (
	"errors"
	"github.com/jinzhu/gorm"
	"github.com/mlogclub/simple"
	"strings"
	"webapp/common"
	"webapp/dao"
	"webapp/model"
)

var UserService = newUserService()

func newUserService() *userService {
	return &userService{}
}

type userService struct {

}


func (this *userService) SignIn(username, password string) (*model.User, error) {
	if  len(username) == 0 {
		return nil, errors.New("username cannot be empty")
	}

	if len(password) == 0 {
		return nil, errors.New("password cannot be empty")
	}

	user := this.GetByUserName(username)

	if user == nil {
		return nil, errors.New("user does not exist")
	}

	if !simple.ValidatePassword(user.Password, password) {
		return nil, errors.New("password is incorrect")
	}

	return user, nil
}

func (this *userService) SignUp(username, password, rePassword string) (*model.User, error) {
	username = strings.TrimSpace(username)
	if err := common.IsValidatePassword(password, rePassword); err != nil {
		return nil, err
	}

	if this.isUsernameExists(username) {
		return nil, errors.New("username:" + username +"is used")
	}

	user := &model.User{
		Username:   simple.SqlNullString(username),
		Password:   simple.EncodePassword(password),
	}
	err := simple.Tx(simple.DB(), func(tx *gorm.DB) error {
		if err := dao.UserDao.Create(tx, user); err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return user, nil
}

func (this *userService) Delete(username string) error {
	if len(username) == 0 {
		return errors.New("username cannot be empty")
	}
	dao.UserDao.Delete(simple.DB(), username)
	return nil
}

func (this *userService) Update(user *model.User)  error {
	err := dao.UserDao.Update(simple.DB(), user)
	return err
}


func (this *userService) GetByUserName(username string) *model.User {
	return dao.UserDao.GetByUserName(simple.DB(), username)
}

// 用户名是否存在
func (this *userService) isUsernameExists(username string) bool {
	return this.GetByUserName(username) != nil
}
